package oocl.ita.eordering.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import oocl.ita.eordering.dao.OrderDao;
import oocl.ita.eordering.po.Order;

@Repository
public class OrderDaoImpl implements OrderDao {
	@PersistenceContext(name = "un")
	private EntityManager em;

	@Override
	public List<Order> showOrderByClientId(int cId) {
		String jpql = "select o from Order o where o.cId=:cId order by o.oId desc";
		@SuppressWarnings("unchecked")
		List<Order> ls = em.createQuery(jpql).setParameter("cId", cId).getResultList();
		if (ls.isEmpty())
			return null;
		else
			return ls;
	}

	@Override
	public int addOrder(Order order) {
		em.persist(order);
		return order.getcId();
	}

	@Override
	public int updateOrder(Order order) {
		Order dbOrder = em.find(Order.class, order.getoId());
		if (order.getFinishTime() != null) {
			dbOrder.setoStatus(order.getoStatus());
			dbOrder.setComplaint(order.getComplaint());
			dbOrder.setFinishTime(order.getFinishTime());
			System.out.println(order.getComplaint());
			System.out.println("yes");
		} else {
			dbOrder.setoStark(order.getoStark());
			;
			System.out.println("no");
		}
		em.merge(dbOrder);
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> showOrderByOrderId(int oId) {
		String jpql = "select o from Order o where o.oId=:oId";
		List<Order> orders = em.createQuery(jpql).setParameter("oId", oId).getResultList();

		if (orders == null)
			return null;
		else
			return orders;
	}

	@Override
	public int complaintOrder(String complaint, int oId) {
		Order dbOrder = em.find(Order.class, oId);
		dbOrder.setComplaint(complaint);
		return dbOrder.getmId();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> findComplaintOrders(Integer cId) {
		String jpql = "from Order o where o.cId=:cId and o.complaint is not null";
		List<Order> list = em.createQuery(jpql).setParameter("cId", cId).getResultList();
		return list;
	}

	@Override
	public List<Order> showOrderByMerchantId(Integer mId) {
		String jpql = "select o from Order o where o.mId=:mId";
		List<Order> orders = (List<Order>) em.createQuery(jpql).setParameter("mId", mId).getResultList();
		if (orders == null)
			return null;
		else
			return orders;
	}

}
